﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace mitasoft.Common.FtpHelpers
{
    public static class Helpers
    {
        public static void CopyFromFtp(string ftpUser, string ftpPass, string ftpFilePath, string diskFilePath)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(ftpUser, ftpPass);

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();

            using (StreamReader reader = new StreamReader(responseStream, Encoding.Default))
            using (StreamWriter writer = new StreamWriter(diskFilePath, false, Encoding.Default))
            {
                writer.Write(reader.ReadToEnd());
            }
        }

        public static string [] ListContent(string user, string pass, string url)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(user, pass);

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            string result = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }
            response.Close();

            return result.Split(new string [] { }, StringSplitOptions.RemoveEmptyEntries);
        }
    }
}
